import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Form, Input, Select, Button, Radio, message, Cascader
} from 'antd';

import { getComBaseInfoById, updateComBaseInfoById, getDictInformation, getDistrictData, getDistrictChineseData, systemComVaseInfoGet } from "../../../services/api";

import './Company.less';

const store = require("store");

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

@connect(state => ({
  companyInfo: state.global.companyInfo,
}))

@Form.create()


export default class Information extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // comId: this.props.location.query.trackid || '',   // 公司ID
      comId: '',
      areas: [],//地区
      submit: false,
      loading: false,
      companyInformationData: {
        comName: '',//公司名字
        telePhone: '',//公司电话
        fax: '',//公司传真
        regProvince: '',//注册地所在省份
        regCity: '',//注册地所在城市
        regArea: '',//注册地所在区/县
        regAddress: '',//公司具体地址
        isBranchCom: '0',//是否分公司
        parentComName: '',//总公司名称
        parentComCerNo: '',//总公司营业执照号
        parentComRep: '',//总公司法人
        parentComTel: '',//总公司联系电话
        economicType: '',//经济类型
        industryType: '',//行业类型
        comType: '',//企业类型
        institutionType: '',//机构类型
        residences: '',//省市区
      },
      economicType: [],//经济类型
      industryType: [],//行业类型
      comType: [],//企业类型
      institutionType: [],//机构类型
      isBranch: '0',
      areaAddress: [110000, 110100, 110102],
    };
  }

  //省市区
  getDistrict = () => {
    getDistrictData().then((data) => {
      console.log('省市区data:', data);
      let areas = data.data.map((val) => {
        return {
          value: val.regionId,
          label: val.regionName,
          children: val.childs.map((valChild) => {
            return {
              value: valChild.regionId,
              label: valChild.regionName,
              children: valChild.childs.map((valChildChild) => {
                return {
                  value: valChildChild.regionId,
                  label: valChildChild.regionName,
                }
              })
            }
          })
        };
      }
      );
      //console.log('areas:'+JSON.stringify(areas));
      this.setState({
        areas: areas,
      });
    })
  };

  componentDidMount() {
    this.companyInformationGet();//是否有信息返回
    this.getEconomic();//经济类型选择
    this.getIndustry();//行业类型选择
    this.getComp();//企业类型选择
    this.getInstitution();//机构类型选择
    this.getDistrict();//省市区选择
  }

  // 通过id获取基本信息
  companyInformationGet = () => {
    getComBaseInfoById({}).then((data) => {
      console.log('基礎信息data:', data);
      //判断获取数据是否为空
      let resultData = data.data;
      if (resultData) {
        this.setState({
          companyInformationData: data.data,
          isBranch: data.data.isBranchCom,
        });

        let s1 = '';
        let s2 = '';
        let s3 = '';

        let province = this.state.companyInformationData.regProvince;
        if (province) {
          getDistrictChineseData({ regionId: province }).then((data) => {
            console.log('9859859859' + JSON.stringify(data.data));
            s1 = (data.data.regionId);
            console.log('s1:' + s1);
          });
        }
        let city = this.state.companyInformationData.regCity;
        if (city) {
          getDistrictChineseData({ regionId: city }).then((data) => {
            s2 = (data.data.regionId);
            console.log('s2:' + s2);
          });
        }
        let area = this.state.companyInformationData.regArea;
        if (area) {
          getDistrictChineseData({ regionId: area }).then((data) => {
            s3 = (data.data.regionId);
            console.log('s3:' + s3);
          })
        }
        setTimeout(() => {
          this.setState({
            areaAddress: [s1, s2, s3],
          });
          console.log(this.state.areaAddress);
        }, 300);
      }
    });
  };


  //获得经济类型
  getEconomic = () => {
    getDictInformation({ codeTypes: 'economicType' }).then((data) => {
      console.log('经济类型data:', data);
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          economicType: data.data.economicType,
        });
      }
    });
  };

  //获得行业类型
  getComp = () => {
    getDictInformation({ codeTypes: 'industryType' }).then((data) => {
      console.log('行业类型data:', data);
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          industryType: data.data.industryType,
        });
      }
    });
  };

  //获得企业类型
  getIndustry = () => {
    getDictInformation({ codeTypes: 'comType' }).then((data) => {
      console.log('企业类型data:', data);
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          comType: data.data.comType,
        });
      }
    });
  };

  //获得机构类型
  getInstitution = () => {
    getDictInformation({ codeTypes: 'institutionType' }).then((data) => {
      console.log('机构类型data:', data);
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          institutionType: data.data.institutionType,
        });
      }
    });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.setState({ submit: true });
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const regData = ['regProvince', 'regCity', 'regArea', 'comId'];
        const regValue = [values.address[0], values.address[1], values.address[2], this.state.comId];
        console.log('111',regData);
        console.log('222',regValue);
        console.log('333',values);
        for (let i = 0; i < regData.length; i++) {
          let key = regData[i];
          let regval = regValue[i] || '0';
          values[key] = regval.toString();
        }
        delete values.address;
        console.log('validateFieldsMore: ', values);
        this.setState({ loading: true });
        updateComBaseInfoById({ ...values }).then((data) => {
          // message.success('提交成功！');
          console.log('updateComBaseInfoById', data);

          if (store.get("saas") !== undefined) {
            systemComVaseInfoGet({}).then(
              response => {
                console.log("企业信息-基础信息-保存公司名称", response);
                const companyInfo = Object.assign({}, this.props.companyInfo);
                companyInfo.comName = response.data.comName;
                console.log("this.props-前", this.props);
                this.props.dispatch({
                  type: "global/companyInfo",
                  payload: companyInfo,
                });
                console.log("this.props===后", this.props);
              },
              errs => {
                console.log("企业信息-基础信息-保存公司名称", errs);
              }
            );
          }

          this.setState({
            companyInformationData: values,
            loading: false
          });
        });
      } else {
        message.error('提交失败！');
        this.setState({ loading: false });
      }
    });
  };
  callback = (key) => {
    console.log(key);
  };

  //验证名称类，限制不能全角输入
  checkFullWidth = (rule, value, callback) => {
    if (value && !(/^[A-Za-z\u4e00-\u9fa5\（\）]{1,50}$/).test(value)) {
      callback('请输入正确的公司名称！');
    } else {
      callback();
    }
  };

  //验证手机号码
  checkPhone = (rule, value, callback) => {
    if ((value && !(/^((0\d{2,3}-\d{7,8})|(1[0-9]{10}))$/).test(value))) {
      callback('请输入正确的联系号码！');
    } else {
      callback();
    }
  };

  //验证传真
  checkFax = (rule, value, callback) => {
    if ((value && !(/^((0\d{2,3}-\d{7,8})|(1[0-9]{10}))$/).test(value))) {
      callback('请输入正确的传真号码！');
    } else {
      callback();
    }
  };


  //验证固定号码
  checkLandlinePhone = (rule, value, callback) => {
    if ((value && !(/^((0\d{2,3}-\d{7,8})|(1[0-9]{10}))$/).test(value))) {
      callback('请输入正确的联系电话！');
    } else {
      callback();
    }
  };

  //经济类型选择
  renderEconomic = () => {
    return this.state.economicType.map((val, key) => {
      return <Option key={key} value={val.codeValue + ""}>{val.label}</Option>;
    });
  };

  //行业类型选择
  renderIndustry = () => {
    return this.state.industryType.map((val, key) => {
      return <Option key={key} value={val.codeValue + ""}>{val.label}</Option>;
    });
  };

  //企业类型选择
  renderCompany = () => {
    return this.state.comType.map((val, key) => {
      return <Option key={key} value={val.codeValue + ""}>{val.label}</Option>;
    });
  };

  //机构类型选择
  renderInstitution = () => {
    return this.state.institutionType.map((val, key) => {
      return <Option key={key} value={val.codeValue + ""}>{val.label}</Option>;
    });
  };

  //是否是分公司选择
  onChangeIsBranch = (e) => {
    console.log('分公司的值是', e.target.value);
    this.setState({
      isBranch: e.target.value,
    });
  };

  checkDetailedAddress = (rule, value, callback) => {
    if ((value && !(/^[A-Za-z0-9\u4e00-\u9fa5]+$/).test(value))) {
      callback('请输入正确的地址！');
    } else {
      callback();
    }
  };

  checkParentComName = (rule, value, callback) => {
    if ((value && !(/^[\u4e00-\u9fa5\（\）]{1,50}$/).test(value))) {
      callback('请输入正确的总公司名称！');
    } else {
      callback();
    }
  };

  checkParentComCerNo = (rule, value, callback) => {
    if ((value && !(/^[A-Za-z0-9]{1,20}$/).test(value))) {
      callback('请输入正确的总公司营业执照号！');
    } else {
      callback();
    }
  };

  checkParentComRep = (rule, value, callback) => {
    if ((value && !(/^[A-Za-z\u4e00-\u9fa5]+$/).test(value))) {
      callback('请输入正确的总公司法人！');
    } else {
      callback();
    }
  };

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };
    return (
      <Form
        onSubmit={this.handleSubmit}
        style={{ marginTop: 24 }}
      >
        <FormItem
          {...formItemLayout}
          label="公司名称"
        >
          {getFieldDecorator('comName', {
            initialValue: this.state.companyInformationData.comName,
            rules: [{
              required: true, message: '请输入公司名称',
            }, {
              validator: this.checkFullWidth
            }],
          })(
            <Input placeholder="请输入" maxLength="50" />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="联系电话"
        >
          {getFieldDecorator('telePhone', {
            initialValue: this.state.companyInformationData.telePhone,
            rules: [{
              required: true, message: '请输入联系电话',
            }, {
              validator: this.checkLandlinePhone
            }],
          })(
            <Input placeholder="请输入" maxLength="12" />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="传真"
        >
          {getFieldDecorator('fax', {
            initialValue: this.state.companyInformationData.fax,
            rules: [{
              validator: this.checkFax
            }],
          })(
            <Input placeholder="请输入" maxLength="12" />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="注册地址"
        >
          {getFieldDecorator('address', {
            // initialValue:[110000],
            initialValue: this.state.areaAddress,
            rules: [{ type: 'array', required: true, message: '注册地址不能为空!' }],
          })(
            <Cascader options={this.state.areas} placeholder="请选择" />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label=" "
          colon={false}
          className="detailedAddress"
        >
          {getFieldDecorator('regAddress', {
            initialValue: this.state.companyInformationData.regAddress,
            rules: [{
              required: true, message: '请输入公司注册详细地址',
            }],
          })(
            <TextArea rows={3} placeholder="请填写公司注册详细地址" maxLength="100" />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="经济类型"
        >
          {getFieldDecorator('economicType', {
            initialValue: this.state.companyInformationData.economicType,
            rules: [{ required: true, message: '请选择经济类型' }],
          })(
            <Select placeholder="请选择">
              {this.renderEconomic()}
            </Select>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="行业类型"
        >
          {getFieldDecorator('industryType', {
            initialValue: this.state.companyInformationData.industryType,
            rules: [{ required: true, message: '请选择行业类型' }],
          })(
            <Select placeholder="请选择" disabled>
              {this.renderIndustry()}
            </Select>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="公司类型"
        >
          {getFieldDecorator('comType', {
            initialValue: this.state.companyInformationData.comType,
            rules: [{ required: true, message: '请选择公司类型' }],
          })(
            <Select placeholder="请选择">
              {this.renderCompany()}
            </Select>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="机构类型"
        >
          {getFieldDecorator('institutionType', {
            initialValue: this.state.companyInformationData.institutionType,
            rules: [{ required: true, message: '请选择机构类型' }],
          })(
            <Select placeholder="请选择" disabled>
              {this.renderInstitution()}
            </Select>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="是否为分公司"
        >
          {getFieldDecorator('isBranchCom', {
            initialValue: this.state.companyInformationData.isBranchCom,
            rules: [{
              required: true, message: '请选择分公司',
            }],
          })(
            <Radio.Group onChange={this.onChangeIsBranch}>
              <Radio value="1">是</Radio>
              <Radio value="0">否</Radio>
            </Radio.Group>
          )}
        </FormItem>
        {this.state.isBranch === '1' ? <FormItem
          {...formItemLayout}
          label="总公司名称"
        >
          {getFieldDecorator('parentComName', {
            initialValue: this.state.companyInformationData.parentComName,
            rules: [{
              required: true, message: '请输入总公司名称',
            }, {
              validator: this.checkParentComName
            }],
          })(
            <Input placeholder="请输入" maxLength="50" />
          )}
        </FormItem> : ''}
        {this.state.isBranch === '1' ? <FormItem
          {...formItemLayout}
          label="总公司营业执照号"
        >
          {getFieldDecorator('parentComCerNo', {
            initialValue: this.state.companyInformationData.parentComCerNo,
            rules: [{
              required: true, message: '请输入总公司营业执照号',
            }, {
              validator: this.checkParentComCerNo
            }],
          })(
            <Input placeholder="请输入" maxLength="20" />
          )}
        </FormItem> : ''}
        {this.state.isBranch === '1' ? <FormItem
          {...formItemLayout}
          label="总公司法人"
        >
          {getFieldDecorator('parentComRep', {
            initialValue: this.state.companyInformationData.parentComRep,
            rules: [{
              required: true, message: '请输入总公司法人',
            }, {
              validator: this.checkParentComRep
            }],
          })(
            <Input placeholder="请输入" maxLength="10" />
          )}
        </FormItem> : ''}
        {this.state.isBranch === '1' ? <FormItem
          {...formItemLayout}
          label="总公司联系电话"
        >
          {getFieldDecorator('parentComTel', {
            initialValue: this.state.companyInformationData.parentComTel,
            rules: [{
              required: true, message: '请输入总公司联系电话',
            }, {
              validator: this.checkPhone
            }],
          })(
            <Input placeholder="请输入" maxLength="12"/>
          )}
        </FormItem> : ''}
        <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
          {/*loading={this.state.loading}*/}
          <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit" >提交</Button>
        </FormItem>
      </Form>
    );
  }
}
